package com.sh.data.engine.domain.base.model.datax;

import com.sh.data.engine.domain.base.model.entity.TbTaskFieldMapEntity;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Data
public class TextReaderParameter extends BaseReaderParameter {
    // 默认文本（txt/csv）分隔符
    private static final String txtSeparator = ",";

    private List<String> path;

    private String encoding = "UTF-8";

    private Integer skipCount = 1;

    private List<Column> columns;

    @Data
    public static class Column implements Serializable {

        private Integer index;

        private String type;

        private String format;

        private String value;

        public Column() {
        }

        public Column(Integer index, String type) {
            this.index = index;
            this.type = type;
        }

        public Column(Integer index, String type, String format) {
            this.index = index;
            this.type = type;
            this.format = format;
        }
    }

    public void setColumns(List<TbTaskFieldMapEntity> fieldMaps) {
        if (path != null && path.size() > 0) {
            String filePath = path.get(0);

            columns = new ArrayList<>();

            if (filePath.endsWith(".txt")) {
                try (FileInputStream inputStream = FileUtils.openInputStream(new File(filePath));
                     BufferedReader reader =
                         new BufferedReader(new InputStreamReader(inputStream, encoding));) {

                    String line = reader.readLine();
                    if (!StringUtils.isEmpty(line)) {
                        String[] fields = line.split(txtSeparator);

                        for (int i = 0; i < fieldMaps.size(); i++) {
                            for (int j = 0; j < fields.length; j++) {
                                if (StringUtils.equalsIgnoreCase(fieldMaps.get(i).getSourceField(), fields[j])) {
                                    Column c = new Column(j, fieldMaps.get(i).getSourceFieldType());
                                    columns.add(c);
                                    break;
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    log.error("读文件异常", e);
                }
            } else if (filePath.endsWith(".csv")) {
                try (BufferedReader reader =
                         new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));) {

                    Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(reader);

                    List<String> headers = new ArrayList<>();

                    for (CSVRecord record : records) {
                        Iterator<String> iterator = record.iterator();
                        while (iterator.hasNext()) {
                            String next = iterator.next();
                            headers.add(next == null ? null : next.trim());
                        }
                        break;
                    }
                    for (int i = 0; i < fieldMaps.size(); i++) {
                        for (int j = 0; j < headers.size(); j++) {
                            if (StringUtils.equalsIgnoreCase(fieldMaps.get(i).getSourceField(), headers.get(j))) {
                                Column c = new Column(j, fieldMaps.get(i).getSourceFieldType());
                                // if ("date".equals(fieldMap.getFieldFromType())) {
                                //  c.setFormat("yyyy/MM/dd");
                                // }
                                columns.add(c);
                                break;
                            }
                        }
                    }
                } catch (IOException e) {
                    log.error("读文件异常", e);
                }
            } else if (filePath.endsWith(".xls") || filePath.endsWith(".xlsx")) {

                InputStream inputStream = null;
                Workbook wb = null;

                try {
                    inputStream = FileUtils.openInputStream(new File(filePath));
                    if (filePath.endsWith(".xls")) {
                        wb = new HSSFWorkbook(inputStream);
                    } else {
                        // wb = StreamingReader.builder().rowCacheSize(1).open(inputStream);
                        wb = new XSSFWorkbook(inputStream);
                    }

                    Sheet sheet = wb.getSheetAt(0);

                    Row currentRow = null;

                    for (Row row : sheet) {
                        currentRow = row;
                        break;
                    }
                    DataFormatter dataFormatter = new DataFormatter();

                    for (int i = 0; i < fieldMaps.size(); i++) {
                        for (int j = 0; j < currentRow.getLastCellNum(); j++) {
                            Cell cell = currentRow.getCell(j);
                            String cellValue = StringUtils.trim(dataFormatter.formatCellValue(cell));
                            if (StringUtils.equalsIgnoreCase(fieldMaps.get(i).getSourceField(), cellValue)) {
                                Column c = new Column(j, fieldMaps.get(i).getSourceFieldType());
                                // if ("date".equals(fieldMap.getFieldFromType())) {
                                //  c.setFormat("yyyy/MM/dd HH:mm:ss");
                                // }
                                columns.add(c);
                                break;
                            }
                        }
                    }

                } catch (IOException e) {
                    log.error("读文件异常", e);
                } finally {
                    try {
                        if (null != inputStream) {
                            inputStream.close();
                        }
                        if (null != wb) {
                            wb.close();
                        }
                    } catch (Exception e) {
                        log.error("关闭流异常", e);
                    }
                }
            }
        }
    }

    /**
     * @description : 根据传过来的字段映射来
     * @author : tinglan.ys
     * @date : 2022/3/18
     */
    public void setColumnsNew(List<TbTaskFieldMapEntity> fieldMaps) {

    /* {
       "type": "long",
       "index": 0    //从本地文件文本第一列获取int字段
    },
    {
       "type": "string",
       "value": "alibaba"  //从TxtFileReader内部生成alibaba的字符串字段作为当前字段
    }*/
        // 测试下载传字段名不行 我也不知道为什么 传index可以，值从map中去拿。
        columns = new ArrayList<>();
        for (TbTaskFieldMapEntity fieldMap : fieldMaps) {
            Column column = new Column();
            column.setIndex(Integer.valueOf(fieldMap.getSourceField()));
            column.setType(fieldMap.getSourceFieldType());
            columns.add(column);

        }
    }
}
